//
//  HSongListView.m
//  HMusicPlayer
//
//  Created by Hament on 14/9/16.
//  Copyright (c) 2014年 HJ. All rights reserved.
//

#import "HSongListView.h"
#import "HCoreConfig.h"
#import "HskinManager.h"
#import "HSongItem.h"
#import "HSongRecordCell.h"
#import "HTriangleView.h"
#import "HSongTableRowView.h"
#import "HPlaylistItem.h"
#import "HSQLManager.h"
#import "HPlayListView.h"
#import "HMainWC.h"
#import "HGroupListView.h"
#import "iTunes.h"
#import "HRenameWC.h"
#import "HID3TagEditWC.h"
#import "TagReader.h"
#import "HJAudioPlayer.h"

#import <OrigamiEngine/ORGMEngine.h>
#import "DOUAudioStreamer.h"

@interface HSongListView()<NSTableViewDataSource,NSTableViewDelegate,NSMenuDelegate>

@property (nonatomic,strong) NSColor * notexistColor;
@property (nonatomic,strong) NSMenu *  pTableMenu;


@property (nonatomic,strong) NSMutableArray * itunesSong;
@property (nonatomic,strong) NSMutableArray * notItunesSong;

@end

@implementation HSongListView

- (id)initWithFrame:(NSRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code here.
    }
    return self;
}

- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];
    
    // Drawing code here.
}




-(void)awakeFromNib {
    
    
    //三角形,正在播放标识符
    self.triangleView=[[HTriangleView alloc] initWithFrame:NSMakeRect(5, 25, 10, 10)];
  
    //文件不存在文字颜色
    self.notexistColor=[NSColor redColor];//RGBA(255, 95, 86, 1.0);

    /*注册允许拖放的类型*/
    self.supportDragTypesArr=@[(id)kUTTypeFileURL,HSONGITEMTYPE];
    [self.tableV registerForDraggedTypes:self.supportDragTypesArr];
    [self.tableV setDraggingSourceOperationMask:NSDragOperationGeneric forLocal:YES];//是否只局限于本地拖放
    
    [self.tableV setMenu:self.pTableMenu];
    
    [self.tableV setDoubleAction:@selector(playSongItem:)];

  
}

#pragma mark  ---------- lazylaoding--------

-(NSMutableArray *)dataSource {
    
    if (!_dataSource) {
        _dataSource=[[NSMutableArray alloc] init];
    }
    return _dataSource;
}


-(NSMenu*)pTableMenu{
    
    if (!_pTableMenu) {
        _pTableMenu=[[NSMenu alloc] init];
        [_pTableMenu setAutoenablesItems:YES];
        _pTableMenu.delegate=self;
    
        
        [_pTableMenu addItemWithTitle:NSLocalizedString(@"file path", nil) action:@selector(goFilePath:) keyEquivalent:@""];
        [_pTableMenu addItemWithTitle:NSLocalizedString(@"rename", nil) action:@selector(fileRename:) keyEquivalent:@""];
        [_pTableMenu addItemWithTitle:NSLocalizedString(@"edit ID3 tag", nil) action:@selector(editID3Tag:) keyEquivalent:@""];
        
    }
    
    
    return _pTableMenu;
}

#pragma mark  ---------- 业务逻辑--------
#pragma mark 播放歌曲
-(void)playSongItem:(NSNotification*)notifi{
    
    
    NSInteger clickrow=[self.tableV clickedRow];
    
    if (clickrow!=-1) {
 
         //-------------本地文件是否存在-----

        HSongItem * sitem=[self.dataSource objectAtIndex:clickrow];

        NSString * localPath=CHECKSTR(sitem.localPath) ;
        if (![localPath isEqualToString:@""]) {
            if ([[NSFileManager defaultManager] fileExistsAtPath:localPath]==NO) {
                 [HCoreConfig alertWithTitle:NSLocalizedString(@"File is not exist", nil) window:[self window]];
                [self.tableV reloadData];
                return;
            }
        }
        
        //先关闭当前歌曲的boomakr
        [[HJAudioPlayer sharePlayer] closeBookmarWithCurrentItem];
        //更改播放列表 & 更改播放面板UI
        [[HJAudioPlayer sharePlayer] configWithSongList:self.dataSource playSongItem:sitem];
        //要先播放,再开始更新界面,因为里面有打开bookmark的操作
        [[HJAudioPlayer sharePlayer] playSongWithSongItem:sitem];
        [[HMainWC shareWc] resetPlayplaneUIWithSongItem:sitem];
        
        [self desselectAllRow];
        [self.tableV reloadData];//
        
        //刷新播放符
        [[HMainWC shareWc].playListView addThePlaySymbol];
        
    }

}


//刷新歌曲列表
-(void)reloadSonglistWithPlaylistItem:(HPlaylistItem*)pitem{
    [self desselectAllRow];
    self.dataSource=[HSQLManager  getSongsByPlaylistItem:pitem];
    
    //如果需要刷新播放列表的话
    NSString * currentplayplistID=[HJAudioPlayer sharePlayer].playListID;
    if([HJAudioPlayer sharePlayer].shouldUpdateQueue==YES && [pitem.syncid isEqualToString:currentplayplistID]){
        [[HJAudioPlayer sharePlayer] updateSongQueueWithSongsArr:self.dataSource];
        
    }
    [HJAudioPlayer sharePlayer].shouldUpdateQueue=NO;
    [self.tableV reloadData];
    
}


//重刷当前数据
-(void)refreshWhenSortTypeChange{

    [self desselectAllRow];
    
    
    NSArray * sortSonglyarr;
    
    //根据排序获取
    if ([[HCoreConfig shareConfig].currentSortType isEqualToString:SortByName]) {
        
        sortSonglyarr= [self.dataSource sortedArrayUsingComparator:^(HSongItem * obj1 ,HSongItem* obj2) {
            if ([obj1.songName compare:obj2.songName]==NSOrderedAscending)
                return  NSOrderedAscending;
            else
                return NSOrderedDescending;
            return NSOrderedSame;
        }];
        
    } else {
        sortSonglyarr= [self.dataSource sortedArrayUsingComparator:^(HSongItem * obj1 ,HSongItem* obj2) {
            if (obj1.syncid.doubleValue > obj2.syncid.doubleValue)
                return NSOrderedDescending;
            else
                return NSOrderedAscending;
            return NSOrderedSame;
        }];
    }
    

    
    
    [self.dataSource removeAllObjects];
    [self.dataSource addObjectsFromArray:sortSonglyarr];
    [self.tableV reloadData];
    
    
    //播放队列也要重排一次
    [[HJAudioPlayer sharePlayer] sortTheSongQueue];
    
    
    
    

}

//插入歌曲
-(void)insertSongsToPlaylist:(HPlaylistItem*)pitem songsPaths:(NSArray*)songsPaths{

    
    //itunes
    if ([pitem.syncid isEqualToString:itunesSyncid]) {
        
        //插入itunes
        
        for (NSString * path in songsPaths) {
            [HCoreConfig importSongToItunesWithpath:path];
        }
        
        [[HMainWC shareWc] addAutoRemoveSuccessReminderWithTitle:nil];
        
    }
    //online
    else  if ([pitem.syncid isEqualToString:onlineSyncid]) {
        //前面拖放做过判断,会提示不允许拖放
        
    }
    //favourite
    else  if ([pitem.syncid isEqualToString:likeSyncid]) {
        NSArray * songitems=[HCoreConfig getSongItemsWithAudiopaths:songsPaths type:1];
        [HSQLManager batchInsertSongsWithPlaylist:pitem songs:songitems db:[HSQLManager shareSqlMg].songDB];
    }
    //自定义播放列表
    else {
    
        NSArray * songitems=[HCoreConfig getSongItemsWithAudiopaths:songsPaths type:0];
        [HSQLManager batchInsertSongsWithPlaylist:pitem songs:songitems db:[HSQLManager shareSqlMg].songDB];
        
        
    
    }




}




-(void)likeSong:(NSButton*)sender{
    

//    NSInteger row = [self.tableV rowForView:sender];
//    HSongItem * songitem = [self.dataSource objectAtIndex:row];
    
    HSongItem * songitem = [(HSongRecordCell *)[sender superview] objectValue];
    

    
    if (songitem) {

        //like
        if (sender.state==NSOnState) {
            songitem.islike=YES;
        }
        //unlike
        else {
            songitem.islike=NO;
            
        }
        
        
  
        //属于itunes歌曲
        if([HCoreConfig checkSongisBelongToItunesWithPath:songitem.localPath]){
            //itunes和数据库都要同步
            [HCoreConfig likeItunesSongWithSongitem:songitem];
            [HSQLManager updateLikeStateWithItem:songitem];//同样更改数据库同步

        }else {
            
            [HSQLManager updateLikeStateWithItem:songitem];//更改数据库同步
            
        }


        //如果当前播放的曲目,需要更新object,播放面板
        HSongItem * tsongitem=[HJAudioPlayer sharePlayer].currentPlaySongItem;
        if(tsongitem){
            if ([tsongitem.syncid isEqualToString:songitem.syncid]) {
                
                tsongitem.islike= songitem.islike;
                [HMainWC shareWc].islikeButton.state=sender.state;
            }

        }
        
        
       // debugLog(@"syncID length:%d",songitem.syncid.length);
        
        
        
    }
    
    //debugLog(@"row:%d,%@",row,songitem.playListSyncID);
}


-(void)toggleAskdeleteItunes:(NSButton*)sender{
    if (sender.state==NSOnState) {
        [HCoreConfig shareConfig].removeItunesAsk=YES;
    } else {
        [HCoreConfig shareConfig].removeItunesAsk=NO;
    }




}

-(void)deleteSongs:(NSButton*)sender{
    
    NSIndexSet * indexs=[self.tableV selectedRowIndexes];
    
    if (indexs.count>0) {
        

        NSArray * arr=[self.dataSource objectsAtIndexes:indexs];
        
        self.itunesSong=[NSMutableArray arrayWithCapacity:10];
        self.notItunesSong=[NSMutableArray arrayWithCapacity:10];
        
        //1.首先要区分对待itunes 和 非itunes的
        HPlaylistItem * pitem=[[HMainWC shareWc].playListView getCurrentSelectPlaylistItem];
        
        //来自itunes
        if ([pitem.syncid isEqualToString:itunesSyncid]) {
            
            [self.itunesSong addObjectsFromArray:arr];//all
        }
        //收藏
        else if ([pitem.syncid isEqualToString:likeSyncid]){
        
            [[HSQLManager shareSqlMg] openSongDB];
            
            [[HSQLManager shareSqlMg] beginTransactionSongDB];
            
            for (HSongItem * sitem in arr) {
                
                //因为在like标签下显示的歌曲是经过除重的,所以需要在数据库里面找一下有没有itunes
                BOOL hasItunes=[HSQLManager findLikeSongsisFromItunes:sitem];
                if (hasItunes) {
                    [self.itunesSong addObject:sitem];
                } else {
                    [self.notItunesSong addObject:sitem];
                }
                
            }

            
             [[HSQLManager shareSqlMg] commitSongDB];
            
            [[HSQLManager shareSqlMg] closeSongDB];
            
            
        }
        //其他
        else {
        
         [self.notItunesSong addObjectsFromArray:arr];//all
        
        }
        

        
        
        //如果询问开关开启,需要询问用户
        
        if([HCoreConfig shareConfig].removeItunesAsk && self.itunesSong.count>0) {
            
            
            NSButton * btn=[[NSButton alloc] initWithFrame:NSMakeRect(0, 0, 250, 30)];
            [btn setButtonType:NSSwitchButton];
            [btn setTitle:NSLocalizedString(@"Ask me when delete itunes music", nil)];
            [btn setBezelStyle:NSThickSquareBezelStyle];
            btn.state=NSOnState;
            [btn setTarget:self];
            [btn setAction:@selector(toggleAskdeleteItunes:)];
            
            
            NSAlert* alert = [NSAlert alertWithMessageText:nil defaultButton:NSLocalizedString(@"delete", nil) alternateButton:NSLocalizedString(@"cancel", nil) otherButton:nil informativeTextWithFormat:NSLocalizedString(@"DeleteItunesDes", nil)];
            [alert setAccessoryView:btn];
            
            alert.alertStyle=NSCriticalAlertStyle;
            [alert beginSheetModalForWindow:[self  window] modalDelegate:self didEndSelector:@selector(sheetDidEnd:resultCode:contextInfo:) contextInfo:nil];
            
            
            
            return;
        }
        
        //删除选中的歌曲
        [self deleteSongsOperationWithIndexSet:indexs];

    }

    
}


-(void)conformDeleteSongs:(NSButton*)sender{
    
    NSIndexSet * indexs=[self.tableV selectedRowIndexes];
    
    if (indexs.count>0) {

        //删除选中的歌曲
        [self deleteSongsOperationWithIndexSet:indexs];

    }
    
    
}


-(void)deleteSongsOperationWithIndexSet:(NSIndexSet*)indexs{

//首先检测删除的歌曲是否涉及当前播放队列
    BOOL isrelatePlayQueue=NO;
    
    HSongItem * playSongitem=[HJAudioPlayer sharePlayer].currentPlaySongItem;
    
    //先找删除的与当前播放列表是否匹配
    for(HSongItem * songitem in self.notItunesSong) {
        if ([playSongitem.syncid isEqualToString:songitem.syncid]) {
            isrelatePlayQueue=YES;
            break;
        }
    }
     //如果是itunes的数据,接着找与文件匹配的
    if(isrelatePlayQueue==NO){
        for(HSongItem * songitem in self.itunesSong) {
            if ([playSongitem.localPath isEqualToString:songitem.localPath]) {
                isrelatePlayQueue=YES;
                break;
            }
        }

    }


    //清除队列里面的歌曲
    [[HJAudioPlayer sharePlayer] deleteWithSongItems:self.notItunesSong fromItunes:NO];
    [[HJAudioPlayer sharePlayer] deleteWithSongItems:self.itunesSong fromItunes:YES];
    
    
    
    //如果找到匹配的,stop正在播放的曲目
    if(isrelatePlayQueue==YES) {

        if ([HJAudioPlayer sharePlayer].currentUsePlayerType==ORGMEngineType) {
            if([HJAudioPlayer sharePlayer].orgmenginePlayer.currentState==ORGMEngineStatePlaying ||[HJAudioPlayer sharePlayer].orgmenginePlayer.currentState==ORGMEngineStatePaused) {
                [[HJAudioPlayer sharePlayer] stopAction];
            }
            
        } else if ([HJAudioPlayer sharePlayer].currentUsePlayerType==DOUAudioType){
        
            if([[HJAudioPlayer sharePlayer].streamPlayerer status]==DOUAudioStreamerPlaying || [[HJAudioPlayer sharePlayer].streamPlayerer status]==DOUAudioStreamerPaused){
            
            
               [[HJAudioPlayer sharePlayer] stopAction];
            
            }
            
        }
        
        //关闭bookmark
        [[HJAudioPlayer sharePlayer] closeBookmarWithCurrentItem];
        
        //把队列的第一首歌作为播放曲目
        if([HJAudioPlayer sharePlayer].currentSongsQueue.count>0) {
        [HJAudioPlayer sharePlayer].currentPlaySongItem=[HJAudioPlayer sharePlayer].currentSongsQueue[0];
        } else {
            [HJAudioPlayer sharePlayer].currentPlaySongItem=nil;
        }
        
        [[HMainWC shareWc] resetPlayplaneUIWithSongItem:[HJAudioPlayer sharePlayer].currentPlaySongItem];
        
    }

    
    //2.删除数据库
    [HSQLManager batchDeleteSongsWithSongItems:self.notItunesSong];
    ;
    
    
    //3.删除itunes的歌曲 & 其他播放列表
    [HCoreConfig deleteItunesSongsWithSongitems:self.itunesSong];
    [HSQLManager batchDeleteSongsHasPathWithSongItems:self.itunesSong];
    
    //4数据源删除
    [self.dataSource removeObjectsAtIndexes:indexs];
    
    [self.tableV deselectAll:nil];
    
    //5.reload 界面删除
    [self.tableV reloadData];
    
    self.itunesSong=nil;
    self.notItunesSong=nil;

}



//取消选择所有行
-(void)desselectAllRow{
    
    
    [self.tableV deselectAll:nil];
    __block NSTableView * tableview=self.tableV;

    [tableview enumerateAvailableRowViewsUsingBlock:^(NSTableRowView *rowView, NSInteger row) {
        
        //第几行第几列
        for (NSInteger column = 0; column < rowView.numberOfColumns; column++) {
            NSView *cellView = [rowView viewAtColumn:column];
            // Is this an NSTableCellView?
            //debugLog(@"row is:%d",row);
            
            HSongRecordCell *tableCellView = (HSongRecordCell *)cellView;
            // It is -- grab the text field and bold the font if selected
            NSTextField * songTf = tableCellView.songTf;
            NSTextField * durationTf = tableCellView.durationTf;
            NSButton * delbtn=tableCellView.delteBtn;
            
            // HSongItem * songitem=[self.dataSource objectAtIndex:row];

                songTf.textColor=[HCoreConfig shareConfig].currentSkinManager.rightListCellTextColor;
                durationTf.textColor=[HCoreConfig shareConfig].currentSkinManager.rightListCellTextColor;
                [delbtn setHidden:YES];

            
        }
        
    }];

}


//因皮肤改变触发按钮变化
-(void)changeIconInAllCell{
   /*
    return;
  NSDictionary * dic=  [self.tableV registeredNibsByIdentifier];
    
    NSNib * nib=dic[@"songCell"];
    NSArray * arr;
    [nib instantiateWithOwner:nil topLevelObjects:&arr];
    
    
    HSongRecordCell *tableCellView=nil;
    for (id obj in arr) {
        if ([obj isKindOfClass:[HSongRecordCell class]]) {
            tableCellView=(HSongRecordCell*)tableCellView;
        }
        
    }

    if (tableCellView) {
        [tableCellView.likeBtn setImage:[HCoreConfig shareConfig].unlikeSongImg];
        [tableCellView.likeBtn setAlternateImage:[HCoreConfig shareConfig].likeSongImg];
        
        
        [tableCellView.delteBtn setImage:[HCoreConfig shareConfig].delSongNorImg];
        [tableCellView.delteBtn setAlternateImage:[HCoreConfig shareConfig].delSongHltImg];
        
         [self.tableV registerNib:nib forIdentifier:@"songCell"];
    }
    
    
//    return;
//    HSongRecordCell *tableCellView=[self.tableV makeViewWithIdentifier:@"songCell" owner:nil];
//    
//    NSNib * viewNib = [[NSNib alloc] init];
//    [viewNib instantiateWithOwner:tableCellView topLevelObjects:nil];
//    
//    
//    [tableCellView.likeBtn setImage:[HCoreConfig shareConfig].unlikeSongImg];
//    [tableCellView.likeBtn setAlternateImage:[HCoreConfig shareConfig].likeSongImg];
//    
//    
//    [tableCellView.delteBtn setImage:[HCoreConfig shareConfig].delSongNorImg];
//    [tableCellView.delteBtn setAlternateImage:[HCoreConfig shareConfig].delSongHltImg];
//    
//    [self.tableV registerNib:viewNib forIdentifier:@"songCell"];
  */  
}


#pragma mark menu------
-(void)goFilePath:(NSMenuItem*)menuitem{
    NSUInteger clickrow= [self.tableV clickedRow];
    //当点击空白行时
    
    if(clickrow!=-1) {

         HSongItem * entity=[self.dataSource objectAtIndex:clickrow];
        
        
    if (entity.localPath) {
        
        
        if ([[NSFileManager defaultManager] fileExistsAtPath:entity.localPath]==NO){

             [HCoreConfig alertWithTitle:NSLocalizedString(@"File is not exist", nil) window:[self window]];
            
            
            [self.tableV reloadData];//然红叉即时出现
        return;
        }

        [HCoreConfig openFilesAccessingSecurityScopedWithSongItem:entity];
        
        NSURL * url=[NSURL fileURLWithPath:entity.localPath];
        
        //debugLog(@"path:%@\nurl:%@",entity.localPath,url);
        [url startAccessingSecurityScopedResource];
        [[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:@[url]];
       
        //如果是当前播放的曲目,不关闭
        HSongItem * si=[HJAudioPlayer sharePlayer].currentPlaySongItem;
        if (si) {
            if (![si.localPath isEqualToString:entity.localPath]) {
                [HCoreConfig stopFilesAccessingSecurityScopedWithSongItem:entity];
            }
        }

    }
    
    
    }
}


-(void)fileRename:(NSMenuItem*)menuitem{
    
    NSUInteger clickrow= [self.tableV clickedRow];
    //当点击空白行时
    
    if(clickrow!=-1) {

         __block   HSongItem * sitem=[self.dataSource objectAtIndex:clickrow];
        
        

        //online的歌曲不允许修改
        if ([sitem.playListSyncID isEqualToString:onlineSyncid]) {
            
            [HCoreConfig alertWithTitle:NSLocalizedString(@"InvalidOperationDesForOnlineItem", nil) window:[self window]];
            
            return;
            
        }

        //判断是否来自itunes
        BOOL  isfromItunes= [HCoreConfig checkSongisBelongToItunesWithPath:sitem.localPath] ? YES :NO;
        
        HRenameWC * wc=[[HRenameWC alloc] initWithWindowNibName:@"HRenameWC"];
        wc.currentSongSyncid=sitem.syncid;
        [self.window addChildWindow:wc.window ordered:NSWindowAbove];
        [wc.window setFrameOrigin:NSMakePoint(CGRectGetMinX(self.window.frame)+(CGRectGetWidth(self.window.frame)-260)/2,CGRectGetMinY(self.window.frame)+200)];
        wc.nameTf.stringValue=sitem.songName;
       
        __block   HSongListView * weakelf=self;
       // __block
        wc.renameHandeler=^(NSString * name) {

            //由itunes来修改
            if (isfromItunes && ![sitem.localPath isEqualToString:@""]) {
                
                //该方法顺便把对象路径一并修改,以及数据库相关影响的项也会一并修改,播放队列也被修改
                [HCoreConfig editItunesNameSongWithSongitem:sitem andNewname:name];

                sitem.songName=name;
                [weakelf.tableV reloadData];
                
                
            }
            //修改本地数据库
            else {
                
                sitem.songName=name;
                //播放队列更改
                [[HJAudioPlayer sharePlayer] updateQueueSongName:name path:sitem.localPath oldPath:sitem.localPath];
                [HSQLManager updateSongNameWithItem:sitem];
                 [weakelf.tableV reloadData];
            }
        
        };
        
        [[HCoreConfig shareConfig].holdWindoControllerArr addObject:wc];
         [NSApp runModalForWindow:wc.window];

        
        
        
    }
    
    
}

-(void)editID3Tag:(NSMenuItem*)menuitem{
    
    NSUInteger clickrow= [self.tableV clickedRow];
    //当点击空白行时
    
    if(clickrow!=-1) {
        //online 要限制
        __block   HSongItem * sitem=[self.dataSource objectAtIndex:clickrow];

        if ([sitem.playListSyncID isEqualToString:onlineSyncid]) {

          [HCoreConfig alertWithTitle:NSLocalizedString(@"InvalidOperationDesForOnlineItem", nil) window:[self window]];

            return;
            
        }
        
     BOOL  openSuccess=[HCoreConfig openFilesAccessingSecurityScopedWithSongItem:sitem];//打开bookmark
        
        //如果文件无法读取,不存在或者权限问题又或者taglib不支持
        if (openSuccess==NO) {
            [HCoreConfig alertWithTitle:NSLocalizedString(@"TagAccessFailed", nil) window:[self window]];
            
            return;
        }
        
        
        
         TagReader * tager=[[TagReader alloc] initWithFileAtPath:sitem.localPath];
        
        if ([tager fileIsValid]) {
            
            //找到将要修改的filetack
           iTunesFileTrack * editFileTrack;
            //旧的路径
            NSString * oldPath=sitem.localPath;
            
            //debugLog(@"name:%@,path:%@",editFileTrack.name,editFileTrack.location);
            BOOL  isfromItunes= [HCoreConfig checkSongisBelongToItunesWithPath:sitem.localPath] ? YES :NO;
            
            //要在被修改前获取
            if(isfromItunes){
             editFileTrack=[HCoreConfig getItunesFiletrackWithPath:sitem.localPath];
            
            }
            
            
            __block   HSongListView * weakelf=self;
            
            HID3TagEditWC * wc=[[HID3TagEditWC alloc] initWithWindowNibName:@"HID3TagEditWC"];
            wc.currentEditsongItem=sitem;
            //修改名字比较特别
            wc.id3TagHandel=^(NSString * name) {
                
                //由itunes来修改
                if (isfromItunes) {

                    //这时候其实已经修改成功
                    NSString * thenewPath=[editFileTrack.location path];//路径已经修改了,但editFileTrack的name好像没修改到
                    
                    //itunes改变,播放列表要跟着改变
                    [HSQLManager updateSongName:name path:thenewPath oldPath:oldPath];
                    
                    //播放队列更改
                    [[HJAudioPlayer sharePlayer] updateQueueSongName:name path:thenewPath oldPath:oldPath];
                    
                    //debugLog(@"edit name:%@,path:%@",editFileTrack.name,editFileTrack.location);

                    sitem.songName=name;
                    sitem.localPath=thenewPath;
                    [weakelf.tableV reloadData];//好像没改到排序!下次改~ >_<
                    
                    
                }
                //修改本地数据库
                else {
                    
                    sitem.songName=name;
                    //播放队列更改
                    [[HJAudioPlayer sharePlayer] updateQueueSongName:name path:sitem.localPath oldPath:sitem.localPath];
                    [HSQLManager updateSongNameWithItem:sitem];
                    [weakelf.tableV reloadData];
                }
                
            };
            
            
            
            [self.window addChildWindow:wc.window ordered:NSWindowAbove];
            [wc.window setFrameOrigin:NSMakePoint(CGRectGetMinX(self.window.frame)+(CGRectGetWidth(self.window.frame)-444)/2,CGRectGetMinY(self.window.frame)+50)];
            [wc configTagReader:tager];
            
            
            [[HCoreConfig shareConfig].holdWindoControllerArr addObject:wc];
            [NSApp runModalForWindow:wc.window];
        } else {

            
             [HCoreConfig alertWithTitle:NSLocalizedString(@"TagAccessFailed", nil) window:[self window]];
            
            return;
        
        }
        
        


    
    
    
    }
    
}


#pragma mark drag显示高亮的框------
-(void)displayTheFocusRingFrame:(BOOL)flag{
    
    //[[HMainWC shareWc].listGroupView focusSongList:flag];
 
    
}


//拖入类型限制,文件夹和音频文件
- (NSDictionary *)pasteboardReadingOptions {
    
    
    return @{NSPasteboardURLReadingFileURLsOnlyKey: @YES,
             NSPasteboardURLReadingContentsConformToTypesKey:@[(id)kUTTypeFolder,@"public.audio"]};//kUTTypeFolder
}

- (BOOL)containsAcceptableURLsFromPasteboard:(NSPasteboard *)pasteboard {
    return [pasteboard canReadObjectForClasses:@[[NSURL class]]
                                       options:[self pasteboardReadingOptions]];
}



#pragma mark  ---------- tableview delegate (view based)--------

- (NSInteger)numberOfRowsInTableView:(NSTableView *)tableView{
    
    
    return [self.dataSource count];
}


- (id)tableView:(NSTableView *)tableView objectValueForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row{
    
    return [self.dataSource objectAtIndex:row];
    
}

// This method is optional if you use bindings to provide the data
- (NSView *)tableView:(NSTableView *)tableView viewForTableColumn:(NSTableColumn *)tableColumn row:(NSInteger)row {
    
     //debugLog(@"loop row:%ld",row);
    
    HSongRecordCell *cellView;
    id entity = [self.dataSource objectAtIndex:row];
    

        HSongItem * thentity=(HSongItem*)entity;
        cellView=[tableView makeViewWithIdentifier:@"songCell" owner:nil];
    
    [cellView.likeBtn setImage:[HCoreConfig shareConfig].unlikeSongImg];
    [cellView.likeBtn setAlternateImage:[HCoreConfig shareConfig].likeSongImg];

    [cellView.delteBtn setImage:[HCoreConfig shareConfig].delSongNorImg];
    [cellView.delteBtn setAlternateImage:[HCoreConfig shareConfig].delSongHltImg];

        cellView.songView=self;
    
        NSString * songname=CHECKSTR(thentity.songName);
        cellView.songTf.stringValue=[NSString stringWithFormat:@"%ld.%@",row+1,songname];
        cellView.songTf.textColor=[HCoreConfig shareConfig].currentSkinManager.rightListCellTextColor;

        NSString * displayTime=[HCoreConfig convertMileSecond:thentity.songDuration];
        cellView.durationTf.stringValue=displayTime;
        cellView.durationTf.textColor=[HCoreConfig shareConfig].currentSkinManager.rightListCellTextColor;
    
        cellView.delTf.textColor=self.notexistColor;
    
//    NSString * path=[thentity.localPath stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    //debugLog(@"thentity.localPath:%@",thentity.localPath);
    
    //文件不存在时,显示红色
    if ([[NSFileManager defaultManager] fileExistsAtPath:thentity.localPath]) {
        //cellView.songTf.textColor=[HCoreConfig shareConfig].currentSkinManager.rightListCellTextColor;
        cellView.delTf.stringValue=@"";
    } else {
        //cellView.songTf.textColor= self.notexistColor;
        cellView.delTf.stringValue=@"X";
    }
    
    //如果收藏了,显示状态
    if(thentity.islike){
        [cellView.likeBtn setState:NSOnState];
        
    } else {
        [cellView.likeBtn setState:NSOffState];
    }
    
    
    
//    if(row%2==0){
//        [cellView refreshBGcolorWithColor:[HCoreConfig shareConfig].currentSkinManager.rightListCellBGColor1];
//    
//    } else {
//        [cellView refreshBGcolorWithColor:[HCoreConfig shareConfig].currentSkinManager.rightListCellBGColor2];
//    }
    

    
    //处理播放标识符
    
    //正在播放的歌曲的path
    HSongItem * songItem=[HJAudioPlayer sharePlayer].currentPlaySongItem;
    
    
    if (songItem) {
        NSString * path=songItem.localPath;
        
        if ([[HJAudioPlayer sharePlayer].playListID isEqualToString:thentity.playListSyncID]&&[path isEqualToString:thentity.localPath] ) {
            
            [cellView addSubview:self.triangleView];
        }else {
            //由于cell会重用,所以需要处理
            NSView *view=[cellView viewWithTag:playTringleViewTag];
            
            if (view) {
                [view removeFromSuperview];
            }
            
        }
        
    } else {
    
        //由于cell会重用,所以需要处理
        NSView *view=[cellView viewWithTag:playTringleViewTag];
        if (view) {
            [view removeFromSuperview];
        }
   

    }

    return cellView;
    
}





//rowview view-base下使用
- (NSTableRowView *)tableView:(NSTableView *)tableView rowViewForRow:(NSInteger)row {
    
    HSongTableRowView * rowView=[tableView makeViewWithIdentifier:NSTableViewRowViewKey owner:nil ];
    
    if(row%2==0){
        rowView.customBGColor=[HCoreConfig shareConfig].currentSkinManager.rightListCellBGColor1;

    } else {
        rowView.customBGColor=[HCoreConfig shareConfig].currentSkinManager.rightListCellBGColor2;
    }
    

    
    return rowView;
}



- (void)tableViewSelectionDidChange:(NSNotification *)notification {
   
 
   
     NSTableView * tableview=[notification object];
      /*
     NSIndexSet * selectindexset= [tableview selectedRowIndexes];
     //当点击空白行时
     if ([selectindexset count]==0) {
     //第几行第几列
     [tableview enumerateAvailableRowViewsUsingBlock:^(NSTableRowView *rowView, NSInteger row) {
     for (NSInteger column = 0; column < rowView.numberOfColumns; column++) {
     NSView *cellView = [rowView viewAtColumn:column];
     // Is this an NSTableCellView?
     if ([cellView isKindOfClass:[MacClientCell class]]) {
     MacClientCell *tableCellView = (MacClientCell *)cellView;
     // It is -- grab the text field and bold the font if selected
     NSTextField * nametextField = tableCellView.nameTf;
     NSTextField * companyxtField = tableCellView.companyTf;
     NSButton   * deleteBtn= tableCellView.deleteBtn;
     
     nametextField.textColor=[NSColor blackColor];
     companyxtField.textColor=[NSColor lightGrayColor];
     rowView.backgroundColor=[NSColor clearColor];
     [deleteBtn setHidden:YES];
     
     }
     }
     
     }];
     return;
     }
     
     
     // NSInteger theselectRow=[tableview selectedRow];
     // debugLog(@"selected row:%ld",theselectRow);
     
     */
     [tableview enumerateAvailableRowViewsUsingBlock:^(NSTableRowView *rowView, NSInteger row) {
     
     //第几行第几列
     for (NSInteger column = 0; column < rowView.numberOfColumns; column++) {
     NSView *cellView = [rowView viewAtColumn:column];
     // Is this an NSTableCellView?

     HSongRecordCell *tableCellView = (HSongRecordCell *)cellView;
     // It is -- grab the text field and bold the font if selected
     NSTextField * songTf = tableCellView.songTf;
     NSTextField * durationTf = tableCellView.durationTf;
         NSButton * delbtn=tableCellView.delteBtn;
         
        // HSongItem * songitem=[self.dataSource objectAtIndex:row];

             if (rowView.selected) {
                 
                 songTf.textColor=[HCoreConfig shareConfig].currentSkinManager.rightListCellHighlightTextColor;
                 durationTf.textColor=[HCoreConfig shareConfig].currentSkinManager.rightListCellHighlightTextColor;
                 [delbtn setHidden:NO];
             } else {
                 songTf.textColor=[HCoreConfig shareConfig].currentSkinManager.rightListCellTextColor;
                 durationTf.textColor=[HCoreConfig shareConfig].currentSkinManager.rightListCellTextColor;
                 [delbtn setHidden:YES];
                 
             }
 
     }

     }];
     

}



#pragma mark -----拖放有关的代理-----
//如果实现了该方法(tableView:writeRowsWithIndexes:toPasteboard:不会再调用),当tableview作为dragsource时,会把选中的行的实体类自动写入pasteboard
//- (id<NSPasteboardWriting>)tableView:(NSTableView *)tableView pasteboardWriterForRow:(NSInteger)row {
//    
//    
//    
//    return self.dataSource[row];
//    
//}

- (BOOL)tableView:(NSTableView *)tableView writeRowsWithIndexes:(NSIndexSet *)rowIndexes toPasteboard:(NSPasteboard *)pboard{

    

   __block NSMutableArray * arr=[NSMutableArray arrayWithCapacity:10];

//    
//    [rowIndexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
//        
//        HSongItem * songitem=[self.dataSource objectAtIndex:idx];
//        [arr addObject:songitem];
//
//        
//    }];
//
//    

    NSArray *songitems = [self.dataSource objectsAtIndexes:rowIndexes];
    for (HSongItem * songitem in songitems) {

        //NSData * data=[NSData dataWithContentsOfFile:CHECKSTR(songitem.localPath)];
         [arr addObject:songitem];
    }

    [pboard writeObjects:arr];


    return YES;
}


//1,这个方法只有拖拽源为tableview时才执行
- (void)tableView:(NSTableView *)tableView draggingSession:(NSDraggingSession *)session willBeginAtPoint:(NSPoint)screenPoint forRowIndexes:(NSIndexSet *)rowIndexes {
    //    NSUInteger len = ([rowIndexes lastIndex]+1) - [rowIndexes firstIndex];
    //    _objectRange = NSMakeRange([rowIndexes firstIndex], len);
    //    _currentlyDraggedObjects = [self.datasource objectsAtIndexes:rowIndexes];
    
    //注册自定义可拖放类型
    //[session.draggingPasteboard setData:[NSData data] forType:HSONGITEMTYPE];//这句话会引起重写选中的第一项里的pasteboard内容
    //debugLog(@"drag begin");
    
}


//拖放结束后
- (void)tableView:(NSTableView *)tableView draggingSession:(NSDraggingSession *)session endedAtPoint:(NSPoint)screenPoint operation:(NSDragOperation)operation {
    
    
    
    //debugLog(@"[HMainWC shareWc].window.frame:%@",NSStringFromRect([HMainWC shareWc].window.frame));
   
    
    //方法一,直接用内部坐标来比较
    /*
    NSPoint windowPoint = [[HMainWC shareWc].window mouseLocationOutsideOfEventStream];
   // NSPoint localPoint = [[HMainWC shareWc].rootContentView convertPoint:windowPoint fromView:nil];
    if (![[HMainWC shareWc].rootContentView mouse:windowPoint inRect:[[HMainWC shareWc].rootContentView visibleRect]]) {
        
        debugLog(@"屏幕外 ");
        
    } else {
    
    debugLog(@"屏幕里面");
    
    }
    */
    
    
    //方法二,用屏幕坐标比较
    
    if(NSPointInRect(screenPoint, [HMainWC shareWc].window.frame))  {

        
    } else {

        
        
        //session.draggingFormation
        
        
        NSPasteboard* zPBoard = [session draggingPasteboard];
        

        NSString * zStrAvailableType = [zPBoard availableTypeFromArray:self.supportDragTypesArr];//该方法按顺序
        if ( UTTypeConformsTo((__bridge CFStringRef)zStrAvailableType, kUTTypeURL)) {
        
            NSURL * url=[NSURL URLFromPasteboard:zPBoard];
        
        debugLog(@"url:%@",url.path);
        
        
        }

        
        else if ([zStrAvailableType compare:HSONGITEMTYPE] == NSOrderedSame ) {
        
        
        
     
        
        }
        
        
        
        
    }
    
}




// 2.确定拖拽的动作信息,该方法会随着拖放位置改变而执行
- (NSDragOperation)tableView:(NSTableView *)tableView validateDrop:(id<NSDraggingInfo>)info proposedRow:(NSInteger)row proposedDropOperation:(NSTableViewDropOperation)dropOperation {
   // NSLog(@"row:%d,song opera:%lu",row,dropOperation);
    
    /*
     if (dropOperation == NSTableViewDropAbove && (_objectRange.location > row || _objectRange.location+_objectRange.length < row)) {
     if ([info draggingSource] == tableView) {
     //如果移动到外面
     if ([info draggingSourceOperationMask] == NSDragOperationCopy) {
     info.animatesToDestination = YES;
     return NSDragOperationCopy;
     }
     
     else {
     return NSDragOperationMove;
     }
     }
     //如果不是tableview作为拖动源,也就是说人家拖进来
     else {
     if ([self containsAcceptableURLsFromPasteboard:[info draggingPasteboard]]) {
     info.animatesToDestination = YES;
     return NSDragOperationCopy;
     }
     }
     }
     */
   // NSLog(@"Htab:[info draggingSource]:%@",[info draggingSource]);
    
    

    
    
    //如果只想限定加在最后
    /*
     [self.tv setDropRow:[self.datasource count] dropOperation:NSDragOperationGeneric];
     return NSDragOperationGeneric;
     */
    
    //debugLog(@"ewewee");
    

    //如果当前为online分类 ,暂时不能添加
    
      HPlaylistItem * ppitem=[[HMainWC shareWc].playListView getCurrentSelectPlaylistItem];
    
    if ([ppitem.syncid isEqualToString:onlineSyncid]) {
        [[HMainWC shareWc] addAutoRemoveFailReminderWithTitle:NSLocalizedString(@"Can not drag into \"online\" category", nil)];
        [self displayTheFocusRingFrame:NO];
      return NSDragOperationNone;
    }
    
    
    
    NSDragOperation result=NSDragOperationCopy;
    
    id dragSource=[info draggingSource];//拖放源头
    
    //内部不允许拖放,但可以拖出去
    if (dragSource == self.tableV){
        info.animatesToDestination = YES;//动画
        [self displayTheFocusRingFrame:NO];
        return NSDragOperationNone;
        
    }
    //app 外部拖放
    else {
        
        //1.只允许拖放到最后的位置
        
        if ([self containsAcceptableURLsFromPasteboard:[info draggingPasteboard]]) {
            [self.tableV setDropRow:self.dataSource.count dropOperation:NSDragOperationGeneric];
            //debugLog(@"YEsYEsYEsYEs ");
            
        } else {
            //debugLog(@"nononononononononono ");
            [self displayTheFocusRingFrame:NO];
        return NSDragOperationNone;
        }
        
        
        
        
        
    }
    
    [self displayTheFocusRingFrame:YES];
    return result;
}




//该方法会update拖放的item信息 ,这里可以实时更新拖放item的显示cell布局,cell的位置
- (void)tableView:(NSTableView *)tableView updateDraggingItemsForDrag:(id<NSDraggingInfo>)draggingInfo {
    
    /*
     [draggingInfo enumerateDraggingItemsWithOptions:0 forView:tableView classes:classes searchOptions:nil usingBlock:^(NSDraggingItem *draggingItem, NSInteger idx, BOOL *stop) {
     if ([draggingItem.item isKindOfClass:[DesktopEntity class]]) {
     DesktopEntity *entity = (DesktopEntity *)draggingItem.item;
     draggingItem.draggingFrame = [tableCellView frame];
     draggingItem.imageComponentsProvider = ^NSArray *{
     if ([entity isKindOfClass:[DesktopImageEntity class]])
     [tableCellView.imageView setImage:[(DesktopImageEntity *)entity image]];
     [tableCellView.textField setStringValue:entity.name];
     return [tableCellView draggingImageComponents];
     };
     validCount++;
     } else {
     draggingItem.imageComponentsProvider = nil;
     }
     }];
     
     */
    
}


//鼠标松手,落下操作
- (BOOL)tableView:(NSTableView *)tableView acceptDrop:(id<NSDraggingInfo>)info row:(NSInteger)row dropOperation:(NSTableViewDropOperation)dropOperation {
    //    if (_currentlyDraggedObjects == nil || [info draggingSourceOperationMask] == NSDragOperationCopy) {
    //        [self performInsertWithDragInfo:info row:row];
    //    } else {
    //        [tableView beginUpdates];
    //        [self performDragReorderWithDragInfo:info row:row];
    //        [tableView endUpdates];
    //    }
    
    

    NSPasteboard* zPBoard = [info draggingPasteboard];
//    NSURL *fileURL = [NSURL URLFromPasteboard:zPBoard];
//    debugLog(@"fileURL:%@",fileURL);
    NSString * zStrAvailableType = [zPBoard availableTypeFromArray:self.supportDragTypesArr];//该方法按顺序
    if ( UTTypeConformsTo((__bridge CFStringRef)zStrAvailableType, kUTTypeURL)) {
    
    
        NSArray * arr=[info draggingPasteboard].pasteboardItems;
        NSWorkspace *workspace = [NSWorkspace sharedWorkspace];
         NSFileManager * fileManager=[NSFileManager defaultManager];
        NSMutableArray * songsUrlArr=[NSMutableArray arrayWithCapacity:10];

        //循环每一个文件夹
        for (NSPasteboardItem * pasteItem in arr) {
            id item=[pasteItem stringForType:zStrAvailableType];
            
            NSURL *url = [[NSURL alloc] initWithPasteboardPropertyList:item ofType:zStrAvailableType];
            //debugLog(@"dragurl:%@",url.path);
            NSString *typeIdentifier;
            BOOL getsuccess=[url getResourceValue:&typeIdentifier forKey:NSURLTypeIdentifierKey error:NULL];
            
            //  debugLog(@"typeIdentifier is:%@",typeIdentifier);
            if (getsuccess ) {
                
                //如果是文件夹
                if ([typeIdentifier isEqualToString:(NSString*)kUTTypeFolder]) {
                     NSString * fopath=url.path;
                     NSDirectoryEnumerator *enumerator=[fileManager enumeratorAtPath:fopath];
                     NSString *file;
                    
                    while (file = [enumerator nextObject]) {
                        //NSLog(@"file:%@",[file description]);
                        
                        NSString * filepath=[fopath stringByAppendingPathComponent:file];
                        NSURL * fileurl=[[NSURL alloc] initFileURLWithPath:filepath];
                        NSString * subtypeIdentifier;
                        
                        [fileurl getResourceValue:&subtypeIdentifier forKey:NSURLTypeIdentifierKey error:NULL];
                        if  ([workspace type:subtypeIdentifier conformsToType:@"public.audio"]){
                            [songsUrlArr addObject:filepath];
    
                        }
                        
                        
                    }
 
                }
                //如果是音乐资源
                else if  ([workspace type:typeIdentifier conformsToType:@"public.audio"]){
                    [songsUrlArr addObject:url.path];
                }
                
            }
 
        }
        
        
        
        
        //插入所有音乐资源到播放列表/相应的分类  ,这个操作可能会影响播放队列
        HPlaylistItem * ppitem=[[HMainWC shareWc].playListView getCurrentSelectPlaylistItem];
        
        [[HSQLManager shareSqlMg] openSongDB];
        [self insertSongsToPlaylist:ppitem songsPaths:songsUrlArr];
        [[HSQLManager shareSqlMg] closeSongDB];
        
         [HJAudioPlayer sharePlayer].shouldUpdateQueue=YES;//需要刷新播放列表的话
        
        
        
        
        
        //刷新列表
        [self reloadSonglistWithPlaylistItem:ppitem];
    
    }
    
    return YES;
}


//- (NSArray *)tableView:(NSTableView *)tableView namesOfPromisedFilesDroppedAtDestination:(NSURL *)dropDestination forDraggedRowsWithIndexes:(NSIndexSet *)indexSet{
//    
//    
//    debugLog(@"sadsasadasd");
//    NSArray *songitems = [self.dataSource objectsAtIndexes:indexSet];
//    
//    NSMutableArray * arr=[NSMutableArray arrayWithCapacity:10];
//    for (HSongItem * s in songitems) {
//        [arr addObject:s.localPath];
//    }
//    return arr;
//}


#pragma mark  ----------alertsheet delegate-------
- (void)sheetDidEnd:(NSWindow *)sheet resultCode:(NSInteger)resultCode contextInfo:(void *)contextInfo {
    
    
    if ([sheet isKindOfClass:[NSAlert class]]) {
        /*
         NSAlert* alert= (NSAlert*)sheet;
         NSString * message=alert.informativeText;
         //debugLog(@"message:%@",message);//标题
         */
        if (resultCode == NSAlertDefaultReturn) {
            debugLog(@"delete");
            
            
            [self conformDeleteSongs:nil];
            
        } else if (resultCode ==NSAlertAlternateReturn){
            debugLog(@"cancel");
            
        } else if(resultCode ==NSAlertOtherReturn){
            
        }
    }
    
    
    
    
}
#pragma mark  ----------nsmenu delegate--------

- (void)menuNeedsUpdate:(NSMenu*)menu{
    
    
    //当点击空白行时
    NSUInteger clickrow= [self.tableV clickedRow];
    if (clickrow==-1) {
        return;
    }
    
    

    
}


- (void)menuWillOpen:(NSMenu *)menu {
    
    //空白行不理会 //group 不理会
    NSUInteger clickrow= [self.tableV clickedRow];
    if (clickrow==-1 ) {
        [menu cancelTracking];
    }
    
    
    
    
    
    
}


- (void)menuDidClose:(NSMenu *)menu {
    
    
}


@end
